package springtive.util;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UnicodeUtils {
	
public static Pattern unicodePattern = null;
	
	static
	{
		unicodePattern = Pattern.compile("&#([0-9][0-9]*);");
	}

	public static String decodeUnicodeHtml(String val)
	{
		StringBuffer buffer = new StringBuffer();
		Matcher m = unicodePattern.matcher(val);
		while ( m.find() )
		{
			String g1 = m.group(1);
			m.appendReplacement(buffer, String.valueOf((char)Integer.parseInt(g1)));
		}
		m.appendTail(buffer);

		return buffer.toString();
	}
	
	public static String encodeUnicodeHtml(String val, String charset)
	{
		CharsetEncoder encoder = Charset.forName(charset).newEncoder();
		StringBuffer buffer = new StringBuffer(val);
		int length = buffer.length();
		char ch = 0;
		
		for ( int i = 0 ; i < length ; i++ )
		{
			if ( !encoder.canEncode(ch = buffer.charAt(i)) )
			{
				String newValue = new StringBuffer("&#")
					.append(Integer.toString((int)ch))
					.append(";").toString();
				
				buffer.replace(i, i+1, newValue);
				int append_length = newValue.length() - 1;
				i += append_length;
				length += append_length;
			}
		}
		
		return buffer.toString();
	}
	
	public static String trimByte(String val, int length, String charset) throws Exception
	{
		CharsetEncoder encoder = Charset.forName(charset).newEncoder();
		ByteBuffer tmpBuffer = ByteBuffer.allocate(length);
		CoderResult cr = encoder.encode(CharBuffer.wrap(val), tmpBuffer, true);
		return new String(tmpBuffer.array(), 0, tmpBuffer.position(), charset);
	}
}
